const request   = require('util/request');
const logger    = require('./log');
const fs        = require('fs');
const fileUtils = require('./fileUtil');
const path      = require('path');

module.exports = {
    post: function(options,callback,errback){
        request({
            url: options.url,
            method: "POST",
            json: true,
            body: options.formData,
            headers:options.headers,
        }, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                logger.debug(`Method:[POST]. Status:[Successful]. rspBody:${JSON.stringify(body)}`);
                callback(body);
            }else{
                logger.err(`Method:[POST]. Status:[Failed]. exMsg:${JSON.stringify(response)}`);
                errback(error);
            }
        });
    },

    get: function(options,callback,errback){
        request({
            url:options.url,
            method:'GET',
            headers:options.headers
        },(error, response, body) => {
            if(!error && response.statusCode === 200){
                logger.debug(`Method:[GET] . Status:[Successful]. rspBody:${body}`);
            }else{
                logger.err(`Method:[GET]. Status:[Failed]. exMsg:${err}`);
            }
        })
    },

    /**
     * 上传文件
     */
    upload: function (options,callback,errback) {
        request.post({
            url: options.url,
            formData: options.formData,
            headers: options.headers
        },function (error,response,body) {
            if(error){
                errback(error);
            }else{
                callback(body);
            }
        })
    },

    /**
     * 下载文件
     * @param downloadOpt
     * @param filePath
     * @returns {Promise<unknown>}
     */
    download:function (downloadOpt,filePath) {
        return new Promise(((resolve, reject) => {
            try{
                let url = downloadOpt.tsUrl;
                let ws = fs.createWriteStream(filePath);
                let chunk = 0;
                ws.on('finish',function () {
                    resolve({
                        filePath:filePath,
                        chunkLength:chunk,
                        downloadOpt:downloadOpt
                    });
                });
                let req = request(url,{timeout:10000,strictSSL:false});

                req.pipe(ws);

                req.on('response', (response) => {
                    chunk = response.headers[ 'content-length' ];
                    logger.info(`Chunk length: ${chunk}`);
                });

                req.on('error',function (e) {
                    logger.err(`Request on message error.${e.message}`);
                    reject(e.message);
                });
            }catch(e){
                logger.err(`下载文件超时,跳过`);
                reject({
                    message:e.message,
                    options:downloadOpt
                });
            }
        }))
    },

    /**
     * 下载网络文件到本地
     * @param options
     * @param indexPath
     */
    downloadToFile(options,indexPath){
        return new Promise((async (resolve, reject) => {
            if(!await fileUtils.exists(indexPath)){
                fileUtils.writeFileAsync(indexPath,'');
            }

            let writeStream = fs.createWriteStream(indexPath);
            let readStream = request(options);

            readStream.pipe(writeStream);

            readStream.on('end', function(response) {
                writeStream.end();
            }).on('error',function (error) {
                logger.err(`Request error.. ${error.message}`);
                reject();
            });

            writeStream.on("finish", function() {
                resolve(indexPath);
            })


        }))
    }
};
